<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 17/8/5
 * Time: 下午4:37
 */
namespace app\api\controller\v1;

use app\api\controller\Common;
use think\Controller;
use app\common\lib\exception\ApiException;
use app\common\lib\Aes;
use app\common\lib\IAuth;

/**
 * 客户端auth登录权限基础类库
 * 1.每个接口(需要登录 个人中心  点赞 评论) 都需要去集
 * 2.判定access_user_token是否合法
 * 3.用户信息->>user
 */
class AuthBase extends Common {

  /**
   * 登录用的基本信息
   */
  public $user = [];

  public function _initialize(){
    //调用父类的自动验证
    parent::_initialize();
    if (empty($this->isLogin())) {
      throw new ApiException('您没有登录',401);
    }
  }

  /**
   * [isLogin 判断是否登录]
   * @return boolean [description]
   */
  public function isLogin(){

    if (empty($this->headers['access-user-token'])) {
      return false;
    }

    $obj = new Aes();
    $accessUserToken = $obj->decrypt($this->headers['access-user-token']);
    if (empty($accessUserToken)) {
      return false;
    }
    if (!preg_match("/\|\|/",$accessUserToken)) {
        return false;
    }
    
    list($token,$id) = explode("||",$accessUserToken);
    $user = model('user')->get(['token'=>$token]);
    if (!$user || $user->status != 1) {
      return false;
    }

    //判断toke　有效期
    if ($user->time_out < time()) {
      return false;
    }
    $this->user = $user;
    return true;
  }

}